package com.chj.leetcode.tijie300to350;

public class Code344_ReverseString {
	public static void reverseString(char[] s) {
		int l = 0;
		int r = s.length - 1;
		reverse(s, l, r);
	}

	public static void reverse(char[] chs, int l, int r) {
		while (l < r) {
			char tmp = chs[l];
			chs[l++] = chs[r];
			chs[r--] = tmp;
		}
	}

	public static boolean is0To9(char s) {
		if (s >= '0' && s <= '9') {
			return true;
		}
		return false;
	}

	public static String reverse_vowel(String str) {

		char[] cs = str.toCharArray();
		int n = cs.length;

		char[] numbers = new char[n];
		int numIndex = 0;
		for (int i = 0; i < n; i++) {
//			if (Character.isDigit(cs[i])) {
//				numbers[numIndex++] = cs[i];
//			}

			if (is0To9(cs[i])) {
				numbers[numIndex++] = cs[i];
			}
		}
		numIndex--;

		for (int i = 0; i < n; i++) {
//			if (Character.isDigit(cs[i])) {
//				cs[i] = numbers[numIndex--];
//			}

			if (is0To9(cs[i])) {
				cs[i] = numbers[numIndex--];
			}
		}

		return String.valueOf(cs);
	}

	public static String reverse_vowel02(String str) {

		char[] cs = str.toCharArray();
		char[] rcs = str.toCharArray();
		int n = cs.length;

		reverseString(rcs);

		int j = 0;
		for (int i = 0; i < n; i++) {
//			if (Character.isDigit(cs[i])) {
//				while (!Character.isDigit(rcs[j])) {
//					j++;
//				}
//				cs[i] = rcs[j++];
//			}

			if (is0To9(cs[i])) {
				while (!is0To9(rcs[j])) {
					j++;
				}
				cs[i] = rcs[j++];
			}
		}

		return String.valueOf(cs);
	}

	public String reverseOnlyLetters(String S) {
		char[] chars = S.toCharArray();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < chars.length; i++) {
			char c = chars[i];
			if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
				sb.append(c);
			}
		}
		char[] charArray = sb.toString().toCharArray();
		int index = 0;
		for (int j = chars.length - 1; j >= 0; j--) {
			char c = chars[j];
			if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
				chars[j] = charArray[index++];
			} else {
				continue;
			}
		}
		return new String(chars);
	}

//作者：bobby996
//链接：https://leetcode-cn.com/problems/reverse-only-letters/solution/10000-9324-by-angel-20/
//来源：力扣（LeetCode）
//著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

	public static void main(String[] args) {
		String str = "a132bcd456efg";
		System.out.println(reverse_vowel(str));
		System.out.println(reverse_vowel02(str));
//		a654bcd231efg
	}

}
